import { Component, OnInit } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { CallService } from '../call.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.page.html',
  styleUrls: ['./search.page.scss'],
})
export class SearchPage implements OnInit {
  files = [];
  text = '';
  constructor(
    private callService: CallService,
    private loadingCtrl: LoadingController,
  ) { }

  ngOnInit() { }

  keyDown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.search();
    }
  }

  clean() {
    this.text = '';
    this.files = [];
  }

  async search() {
    if (!this.text) {
      this.clean();

      return;
    }

    const loading = await this.loadingCtrl.create({
      message: '搜索中...',
    });
    await loading.present();


    const fs = await this.callService.call('search', { msg: '搜索中...' }, this.text);
    if (fs) {
      this.files = fs;
    } else {
      this.files.push({
        id: 33,
        name: `/tmp/${this.text}.txt`,
        formatSize: '33KB',
        formatTime: '2021-01-01 01:34:43',
        wordCount: 33,
        hits: [
          { text: 'if has {', line: 13, words: { 0: 2 } },
          { text: '    my name is www', line: 14, words: { 7: 11 } },
          { text: '}', line: 15, words: { 0: 1 } },
        ],
      });
    }

    await loading.dismiss();
  }

  async open(file: string) {
    const err = await this.callService.call('openFile', { msg: '打开文件...' }, file);

    console.log(err);
  }

  async show(file: string) {
    const err = await this.callService.call('showFile', { msg: '显示文件...' }, file);

    console.log(err);
  }
}
